package com.ruijie.camerax

import android.Manifest
import android.annotation.SuppressLint
import android.content.ContentValues
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.util.Size
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.google.common.util.concurrent.ListenableFuture
import com.ruijie.camerax.databinding.ActivityTakePictureBinding
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class TakePictureActivity : AppCompatActivity() {

    companion object {

        private const val TAG = "TakePictureActivity"
        private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
        private val REQUIRED_PERMISSIONS =
            arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO
            )
    }

    private lateinit var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>
    private lateinit var _binding: ActivityTakePictureBinding

    private var cameraProvider: ProcessCameraProvider? = null
    private val cameraSelector = CameraSelector.Builder()
        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
        .build()

    private lateinit var preview: Preview
    private val mPreviewSize = Size(1080, 1920)

    private lateinit var imageCapture: ImageCapture

    private lateinit var registerForActivityResult: ActivityResultLauncher<Array<String>>

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityTakePictureBinding.inflate(layoutInflater)
        setContentView(_binding.root)
        cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        registerForActivityResult =
            registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results ->
                val allPermissionGranted = results.all { it.value }
                if (allPermissionGranted) {
                    startCamera()
                }
            }


        // Request camera permissions
        registerForActivityResult.launch(REQUIRED_PERMISSIONS)

        _binding.apply {
            preview = Preview.Builder()
                .setTargetResolution(mPreviewSize)
                .build()
            preview.setSurfaceProvider(previewV.surfaceProvider)

            btnStart.setOnClickListener {
                capture()
            }
        }
    }


    private fun startCamera() {
        cameraProviderFuture.addListener(Runnable {
            cameraProvider = cameraProviderFuture.get()
            cameraProvider?.let {
                it.unbindAll()
                //配置相机
                imageCapture = ImageCapture.Builder()
                    .setTargetRotation(_binding.previewV.display.rotation)
                    .build()

                it.bindToLifecycle(
                    this@TakePictureActivity,
                    cameraSelector,
                    preview, imageCapture
                )
            }
        }, ContextCompat.getMainExecutor(this))
    }

    private fun capture() {
        val pictureFileName =
            SimpleDateFormat(FILENAME_FORMAT, Locale.CHINA).format(Date()) + ".jpg"
        val file = File(getExternalFilesDir(null), pictureFileName)
        if (!file.exists()) {
            file.createNewFile()
        }
        Log.d(TAG, "capture: $pictureFileName")
        //拍照并保存到系统相册
        val contentValues = ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "NEW_IMAGE");
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
        val outputFileOptions = ImageCapture.OutputFileOptions.Builder(
            contentResolver,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            contentValues
        )
            .build()
        //  拍照保存到自定义相册   这种情况   onImageSaved回调的 ${outputFileResults.savedUri} 是null
        //    val outputFileOptions = ImageCapture.OutputFileOptions.Builder(file)
        imageCapture.takePicture(outputFileOptions,
            ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    // insert your code here.
                    Log.d(TAG, "onImageSaved: ${outputFileResults.savedUri}")

                    Toast.makeText(
                        applicationContext,
                        "照片已保存至 : ${outputFileResults.savedUri}",
                        Toast.LENGTH_SHORT
                    ).show()
                }

                override fun onError(exception: ImageCaptureException) {
                    Log.d(TAG, "onError: $exception")
                }
            })
    }
}